package com.freedy.algorithm.binarySearch;

import java.util.Scanner;

/**
 * @author Freedy
 * @date 2021/4/11 21:01
 */
public class BinarySearch {
    public static void main(String[] args) {
        //测试
        int[] arr={1,3,8,10,11,67,100};
        int index=binarySearch(arr,123);
        System.out.println(index);
    }

    /**
     * 二分查找非递归实现
     * @param arr 要查找的数组
     * @param target 要查找的值
     * @return 找到的索引
     */
    public static int binarySearch(int[] arr,int target){
        int left=0;
        int right=arr.length-1;
        while (left<=right){
            int mid=(left+right)/2;
            if (arr[mid]==target){
                return mid;
            }else if (arr[mid]>target){
                right=mid-1;//向左查找
            }else if (arr[mid]<target){
                left=mid+1;//向右查找
            }
        }
        return -1;
    }

}
